import { login, validateVarCode, qrcodeCallback } from '@/api/user'
import { encrypt } from '@/utils/cryptoAes'
import { selectGroupSetting } from '@/api/ramUser'

const getDefaultState = () => {
  return {
    verifyPassed: false
  }
}
const state = getDefaultState()

const mutations = {}

const afterActionLogin = (context, res) => {
  // 拿到数据，构建树结构(路由菜单分别创建)
  context.commit('base/SET_LOGIN_INFO', res.data, { root: true })
  let menus = []
  let permissions = []
  res.data.menus.forEach(item => {
    if (item.type === 1 || item.type === 2 || item.type === 3) {
      menus.push(item)
    }
    if (item.permission) {
      permissions.push(item.permission)
    }
  })
  context.commit('base/SET_MENUS', menus, { root: true })
  context.commit('base/SET_ROUTER', menus, { root: true })
  context.commit('base/SET_PERMISSIONS', permissions, { root: true })
}

const actions = {
  loginByThird(context, params) {
    console.log("RAM系统开始第三方登录流程", params)
    return new Promise((resolve, reject) => {
      qrcodeCallback(params)
        .then(async res => {
          if (res.data) {
            if (params.redirect?.startsWith('http')) {
              resolve(res.data.token)
            } else {
              afterActionLogin(context, res)
              initSetting(context)
            }
            resolve(res.data.token)
          } else {
            resolve(null)
          }
        })
        .catch(error => {
          console.error("RAM系统第三方登录失败:", error)
          reject(error)
        })
    })
  },
  //登录(账号+密码)
  loginByAccount(context, userInfo) {
    console.log("RAM系统开始登录流程")
    let _userInfo = structuredClone(userInfo)
    _userInfo.password = encrypt(_userInfo.password).toString()
    return new Promise((resolve, reject) => {
      login(_userInfo)
        .then(async res => {
          // 账号或密码过期
          if (res.code === 102010) {
            resolve(false)
            return
          }
          if (res.data) {
            afterActionLogin(context, res)
            initSetting(context)
            resolve(res)
          }
        })
        .catch(error => {
          console.error("RAM系统登录失败:", error)
          reject(error)
        })
    })
  },
  //登录(手机号+验证码)
  loginByPhone(context, userInfo) {
    return new Promise((resolve, reject) => {
      validateVarCode(userInfo)
        .then(res => {
          if (res.data) {
            afterActionLogin(context, res)
            resolve(res)
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

async function initSetting(context) {
  const res = await selectGroupSetting()
  const groupSetting = JSON.parse(res.data)
  context.commit('base/SET_GROUP_SETTING', groupSetting, { root: true })
  const { iconInit } = await import('@ruifox-cms/utils')
  iconInit(groupSetting.publicIcon)
}

export default {
  namespaced: true, //命名空间
  state,
  mutations,
  actions
}
